package app.itgungnir.compose.wan

import android.os.Process
import androidx.multidex.MultiDexApplication
import app.itgungnir.compose.wan.utils.LocalDataStore
import app.itgungnir.compose.wan.utils.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

class WanApp : MultiDexApplication() {

    companion object {
        lateinit var instance: WanApp
        val appScope by lazy { CoroutineScope(SupervisorJob() + Dispatchers.IO) }
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
        Thread.setDefaultUncaughtExceptionHandler(GlobalCrashHandler())
        appScope.launch {
            LocalDataStore.observeLocalData()
        }
    }

    private class GlobalCrashHandler : Thread.UncaughtExceptionHandler {
        override fun uncaughtException(t: Thread, e: Throwable) {
            log(e.stackTraceToString(), "fatal")
            Process.killProcess(Process.myPid())
        }
    }
}
